package com.atguigu.leetcode;

import cn.hutool.core.lang.Console;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

/** https://leetcode-cn.com/problems/two-sum/
 * @Notes
 * @Author gary
 * @Date 2021/11/1 16:07
 **/
public class _1TwoSum {
    int[] nums;
    int target;

    @BeforeEach
    public void before() {
        nums = new int[]{2, 7, 11, 15};
        target = 9;
    }

    @Test
    public void my() {
        int[] ints = twoSum(nums, target);
        Console.log(ints);
    }

    @Test
    public void leetCode() {
        int[] ints = twoSumByLeetCode(nums, target);
        Console.log(ints);
    }

    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if ((nums[i] + nums[j]) == target) {
                    int[] rtn = new int[2];
                    rtn[0] = i;
                    rtn[1] = j;
                    return rtn;
                }
            }
        }
        return new int[2];
    }

    public int[] twoSumByLeetCode(int[] nums, int target) {
        Map<Integer, Integer> hashtable = new HashMap<>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }
}
